var db;
var lessonID = getUrlVars()["leid"];
var vocabularyLessonIDSelected = getLocalStorage('vocabularyLessonIDSelected');
var favourite = 0;
var v_id;
var id_favourite;

if (lessonID == null || lessonID == undefined) {
	if (vocabularyLessonIDSelected == null) { // //Lan chay dau tien : khong
												// co lessonID va
												// lessonForwardSelected -->load
												// nhung bai doc cua lesson dau
												// tien (mac dinh coi la 1)
		lessonID = 1;
		setLocalStorage('vocabularyLessonIDSelected', lessonID);
		// luu trang thai cua cac button (show kanji,Han-Viet,phien am, nghia
		// anh, nghia viet) vao localstorage
		setLocalStorage('showKanji', 'on');
		setLocalStorage('showHan_Viet', 'on');
		setLocalStorage('showPhienAm', 'on');
		setLocalStorage('showMeanVi', 'on');
		setLocalStorage('showMeanEn', 'on');
	} else { // ko phai lan chay dau tien(nhung cung khong co lessonID tren
				// url) -> lay lessonForwardSelected dc luu trong localStorage
		lessonID = vocabularyLessonIDSelected
	}
} else {// lay chay sau, co lessonID tren url -> cap nhat lai
		// lessonForwardSelected
	setLocalStorage('vocabularyLessonIDSelected', lessonID);
}

// connect to database
function connectDB() {
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",
			500000);
	db.transaction(getVocabularyByLesson, errorCB);
}

// function will be called when an error occurred
function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

function successCB() {
	db.transaction(getVocabularyByLesson, errorCB);
}
// get all lesson from db
function getVocabularyByLesson(tx) {
	var sql = "SELECT v_id,v_word,v_hiragana,v_mean_kanji,v_mean_en,v_mean_vi,v_lesson_id,v_note,v_favourite,v_dataversion_id  "
			+ " FROM vocabulary WHERE v_lesson_id=? ";
	tx.executeSql(sql, [ lessonID ], showVocabularyByLesson);
}

// show lesson list in html code
function showVocabularyByLesson(tx, results) {
	getLessonTitle(lessonID).done(function(title) {
		$('#lesson-name').append(title);
	});

	// show/ not show cac item
	var showKanji, showHan_Viet, showPhienAm, showMeanVi, showMeanEn;
	// show kanji
	if (getLocalStorage('showKanji') == 'on')
		showKanji = 'block';
	else
		showKanji = 'none';

	// showHAn_viet
	if (getLocalStorage('showHan_Viet') == 'on')
		showHan_Viet = 'block';
	else
		showHan_Viet = 'none';

	// showPhienAm
	if (getLocalStorage('showPhienAm') == 'on')
		showPhienAm = 'block';
	else
		showPhienAm = 'none';

	// showMeanVi
	if (getLocalStorage('showMeanVi') == 'on')
		showMeanVi = 'block';
	else
		showMeanVi = 'none';

	// showMeanEn
	if (getLocalStorage('showMeanEn') == 'on')
		showMeanEn = 'block';
	else
		showMeanEn = 'none';

	var len = results.rows.length;
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var data = results.rows.item(i);
			if (data.v_favourite == 1) {
				id_favourite = 'ui-icon-favourite';
			} else {
				id_favourite = '';
			}
			
			$('#vocabulary-lesson')
			.append(
					'<li style="height: 120px;" v_id="'+data.v_id+'" class="ui-li-static ui-body-inherit ui-first-child ui-last-child"><fieldset class="ui-list-a"> <div class="ui-block-a" style="position: absolute; top: 7px; right: 60px; left: 45px;">'
							+ '<h5 class="kanji" style="float: left;display:'
							+ showKanji
							+ '">'
							+ data.v_word
							+ '</h5> '
							+ '<h3 class="mean_kanji" style="float: right; font-size: 12px; margin-top: 15px;text-transform:uppercase;display:'
							+ showHan_Viet
							+ '"><span>&nbsp;</span><span>'
							+ data.v_mean_kanji
							+ '</span></h3> '
							+ '<p class="hiragana" style="float: left; clear: both; margin-left: -20px;display:'
							+ showPhienAm
							+ '"><span>&nbsp;</span><span>'
							+ data.v_hiragana
							+ '</span></p> '
							+ '<p class="mean_en" style="float: left; clear: both; margin-left: -20px;display:'
							+ showMeanEn
							+ '"><span>&nbsp;</span><span>'
							+ data.v_mean_en
							+ '</span></p> '
							+ '<p class="mean_vi" style="float: left; clear: both; margin-left: -20px;display:'
							+ showMeanVi
							+ '"><span>&nbsp;</span><span>'
							+ data.v_mean_vi
							+ '</span></p></div>'
							+ '<div class="ui-block-b" style="position: absolute; top: -2px; right: 5px;"><div data-role="controlgroup" data-type="vertical" style="width: 30px;" class="ui-controlgroup ui-controlgroup-vertical ui-corner-all"><div class="ui-controlgroup-controls "> '
							+ '<a id="'
							+ id_favourite
							+ '" href="#" type="favourite" vocabularyid="'
							+ data.v_id
							+ '" onclick="processFavourite('
							+ data.v_id
							+ ');" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-star ui-btn-icon-notext ui-shadow ui-corner-all ui-first-child" role="button"> '+ data.v_id + '</a> '
							+ '<a noteID="'+data.v_id+'" id="noteDialog" href="#write-note"  onclick="writeNote('+data.v_id+');" data-rel="popup" data-position-to="window" data-transition="pop" data-role="button" data-iconpos="notext" data-icon="edit" class="ui-link ui-btn ui-icon-edit ui-btn-icon-notext ui-shadow ui-corner-all ui-last-child" role="button">Edit</a>'
							+ '<a actionID="'+data.v_id+'" id="actionDialog" onclick="addFuntionLink('+data.v_id+');" href="#popupAction" data-rel="popup" data-transition="slideup" data-rel="popup" data-role="button" data-iconpos="notext" class="ui-link ui-btn ui-icon-gear ui-btn-icon-notext ui-shadow ui-corner-all ui-last-child" role="button">Edit</a>'
							+ '</div></div></fieldset></li>');
           }
	} else {
		$('#vocabulary-lesson').append(
				'<div style="margin: 20px; 20px;">Updating...</div>');
	}
}


function addFuntionLink(id){
	$('#actionEdit').attr('href','vocabulary_add.html?id='+id);
	$('#actionDelete').attr('onclick','deleteVocabulary('+id+')');
}

//delete vocabulary
function deleteVocabulary(id){
	this.db.transaction(function(tx) {
		var sql = "DELETE FROM vocabulary WHERE v_id =? ";
		tx.executeSql(sql, [ id ], function(tx, results) {
			$('li[v_id="' + id + '"]').remove();
			$('#vocabulary-lesson').listview('refresh');
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}

//editvocabulary
function editVocabulary(id){
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(function(tx) {
		var sql = "SELECT v_id,v_word,v_hiragana,v_mean_kanji,v_mean_en,v_mean_vi,v_lesson_id,v_note,v_favourite,v_dataversion_id, le_title "
			+ " FROM vocabulary "
			+ " INNER JOIN lesson"
			+ " ON vocabulary.v_lesson_id = lesson.le_id"
			+ " WHERE v_id=?";
		tx.executeSql(sql, [ id ], function(tx, results) {
			var len = results.rows.length;
			var data = results.rows.item(0);
			//neu 1 tu ma v_hiragana va v_mean_kanji de null thi ->katakana. nguoc lai thi kanij type
			if (data.v_hiragana === '' && data.v_mean_kanji === '') {//katakana type
				$("label[id=label_word]").text("Katakana");
				$('#field-mean-kanji').css('display','none');
				$('#field-hiragana').css('display','none');
				
				//chua xu ly dc
				//$("#typeAdd").val("katakana").flipswitch("refresh");
				//$( "#typeAdd value:katakana ").attr('selected','selected');
			/*	$('select option').each(function(){
					var typeAdd = $(this).val();
					console.log('typeAdd ' + typeAdd);
					if (typeAdd == 'katakana') {
						$('option[value="katakana"]').attr("selected","selected");
					}
				});*/
				
				
				//$("#typeAdd option[value='katakana']").attr('selected', 'selected');
				
				
				
				//$("#typeAdd").val("katakana").attr('selected','selected');
				
				
			}else{
				$("label[id=label_word]").text("Kanji");
				$('#field-mean-kanji').css('display','block');
				$('#field-hiragana').css('display','block');
				
				//chua xu ly dc
				//$( "#typeAdd value:kanji").attr('selected','selected');
				//$("#typeAdd").val("kanji").flipswitch("refresh");
				//$("#typeAdd").val("kanji").attr('selected','selected');
				
				/*$('select option').each(function(){
					var typeAdd = $(this).val();
					console.log('typeAdd ' + typeAdd);
					if (typeAdd == 'kanji') {
						$('option[value="kanji"]').attr("selected","selected");
					}
				});*/
				
				
				//$("#typeAdd option[value='kanji']").attr('selected', 'selected');
				
				$('#hiragana').attr('value',data.v_hiragana);
				$('#mean_kanji').attr('value',data.v_mean_kanji);
			}
			
			$('#word').attr('value',data.v_word);
			$('#mean_vi').attr('value',data.v_mean_vi);
			$('#mean_en').attr('value',data.v_mean_en);
			$('#remember').text(data.v_note);
			
			//xu ly dung thang lesson 
			var lesson_id = data.v_lesson_id;
			
			
			$("#select-lesson-list option[value='"+lesson_id+"']").attr('selected', 'selected');
			$('#select-lesson-list').selectmenu('refresh');
			
		/*	$('#select-lesson-list option').each(function(){
				var lessonValueId = $(this).val();
				console.log('lessonValueId ' + lessonValueId);
				
				alert('fsd');
				
				if (lessonValueId == lesson_id) {
					$('a[lesson_id="' + lesson_id + '"]').attr("selected","selected");
				}
			});*/
			
			console.log('lesson ' + data.v_lesson_id);

			
			
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}



function writeNote(id){
	var currentNote;
	idClicked = id;
	var inputText;
	//set id cho moi textarea
	$('#note-content').attr('textareaid',idClicked);
	$('textarea[textareaid="' + idClicked + '"]').val('');
	
	//lay ve v_note cua vocabulary co v_id = id
	this.db.transaction(function(tx) {
		var sql = "SELECT v_note FROM vocabulary WHERE v_id =? ";
		tx.executeSql(sql, [ idClicked ], function(tx, results) {
			//$('#note-content').val(results.rows.item(0).v_note);
			currentNote = results.rows.item(0).v_note;
			$('#note-content[textareaid="'+idClicked+'"]').val(currentNote);
			//when click ok button
			    $("#writeNoteOK").click(function(event,callback){
			        $( this ).unbind( event );
			        db.transaction(function(tx) {  
						var textareIDSelecting = $('#note-content').attr('textareaid');
						inputText = $('#note-content[textareaid="'+idClicked+'"]').val(); // chi lay ve du lieu trong textarea co noteid = id
							//kiem tra xem inputText co giong vs chuoi ban dau khong --> th use mo len n khong them bat cu character nao ca ma press ok button
							if (inputText.toString() !==  currentNote) {
								var sql = "UPDATE vocabulary SET v_note = '"+inputText+"' WHERE v_id = " + textareIDSelecting;
					            //return false;
						        tx.executeSql(sql, [], function(tx, results) {
						        	console.log('updatea ok');
						        	//return(false);
						        	//successUpdateNoteToast();
						        }, function(tx, error) {
							        alert("Error: " + error);
						        });
							}
			        }, function(tx, error) {
				         alert("Processing favourite error: " + error);
				         //errorUpdateNoteToast();
			        });
			    });
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}


function updateVocabulary(id){
	var v_lesson_id = $("#select-lesson-list option[selected='selected']").val();
	var v_word = $('#word').val();
	var v_hiragana = $('#hiragana').val();
	var v_mean_kanji = $('#mean_kanji').val();
	var v_mean_vi = $('#mean_vi').val();
	var v_mean_en = $('#mean_en').val();
	var v_note = $('#remember').val();
	var v_favourite = 0;
	var v_dataversion = 0;
	
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(function(tx) {
		var sql = "UPDATE vocabulary " +
				  "SET v_word='"+v_word+"', v_hiragana='"+v_hiragana+"', v_mean_kanji = '"+v_mean_kanji+"',v_mean_vi = '"+v_mean_vi+"', v_mean_en = '"+v_mean_en+"', v_note = '"+v_note+"',v_lesson_id = '"+v_lesson_id+"', v_favourite = 0, v_dataversion_id = 0 " +
				  "WHERE v_id= " + id;
		tx.executeSql(sql, [], function(tx, results) {
			$(location).attr('href', "vocabulary.html");
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}

function addVocabulary(v_lesson_id){
	var v_word = $('#word').val();
	var v_hiragana = $('#hiragana').val();
	var v_mean_kanji = $('#mean_kanji').val();
	var v_mean_vi = $('#mean_vi').val();
	var v_mean_en = $('#mean_en').val();
	var v_note = $('#remember').val();
	console.log(v_word);
	console.log('v_note = ' + v_note);
	var v_favourite = 0;
	var v_dataversion = 0;
	
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(function(tx) {
		var sql = "INSERT INTO vocabulary (v_word,v_hiragana,v_mean_kanji,v_mean_en,v_mean_vi,v_lesson_id,v_note,v_favourite,v_dataversion_id ) " +
				  "VALUES  ('"+v_word+"','"+v_hiragana+"','"+v_mean_kanji+"','"+v_mean_en+"','"+v_mean_vi+"','"+v_lesson_id+"', '"+v_note+"','0','0')";
		tx.executeSql(sql, [], function(tx, results) {
			$(location).attr('href', "vocabulary.html");
			var msg = new Android_Toast({content: 'Đã đánh dấu yêu thích'});
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}

function successUpdateNoteToast(){
	var msg = new Android_Toast({content: 'Đã đánh dấu yêu thích'});
}

function errorUpdateNoteToast(){
	//var toast2 = new Android_Toast({content: 'Bỏ đánh dấu yêu thích', duration: 4000, position: 'top'});
	var msg = new Android_Toast({content: 'Add favourite error'});
}

function processFavourite(id) {
	v_id = id;
	this.db.transaction(function(tx) {
		var sql = "SELECT v_favourite FROM vocabulary WHERE v_id =? ";
		tx.executeSql(sql, [ v_id ], function(tx, results) {
			var len = results.rows.length;
			if (results.rows.item(0).v_favourite == 1) {// hien tai dang
														// favourited ->
														// unfavourite
				favourite = 0;
			} else {
				favourite = 1;
			}
			db.transaction(updateFavourite, errorCB);
		});
	}, function(tx, error) {
		alert("Processing favourite error: " + error);
	});
}



var vocabularyid;
function updateFavourite(tx) {
	var sql = "UPDATE vocabulary SET v_favourite = " + favourite
			+ " WHERE v_id =? ";
	tx.executeSql(sql, [ v_id ], function(tx, results) {
		if (favourite == 1) {
			$('#vocabulary-lesson a').each(function(){
				vocabularyid = $(this).attr('vocabularyid');
				if (vocabularyid == v_id) {
					$('a[vocabularyid="' + v_id + '"]').attr("id","ui-icon-favourite");
				}
			});
		}else{
			$('#vocabulary-lesson a').each(function(){
				vocabularyid = $(this).attr('vocabularyid');
				if (vocabularyid == v_id) {
					$('a[vocabularyid="' + v_id + '"]').attr("id","");
				}
			});
		}
	}, function(tx, error) {
		errorFavouriteToast();
	});
}
